<template>
  <div class="addDept">
    <el-form :model="addForm" :rules="rules" ref="ruleForm" label-width="90px">
      <el-form-item label="部门名称: " prop="deptName">
        <el-input v-model="addForm.deptName" size="mini" style="width: 80%;" clearable placeholder="请输入部门名称"></el-input>
      </el-form-item>
      <el-form-item label="上级部门: " prop="pid">
        <el-select v-model="addForm.pid" size="mini" style="width: 80%;" placeholder="请选择上级部门" clearable filterable>
          <el-option
            v-for="(item,index) in deptList"
            :key="index"
            :label="item.deptName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <p style="text-align: center;">
        <el-button size="mini" @click="cancle">取消</el-button>
        <el-button size="mini" type="primary" @click="submitForm('ruleForm')">确认</el-button>
      </p>
    </el-form>

  </div>
</template>

<script>
  export default {
    name: 'addDept',
    data() {
      return {
        addForm: {},
        rules: {
          deptName: [{ required: true, message: '请输入部门名称', trigger: 'blur' },],
          pid: [{ required: true, message: '请输选择上级部门', trigger: 'blur' },],
        },
        deptList: [],
      }
    },
    mounted() {
      this.getDepartmentList();
    },
    methods: {
      getDepartmentList() {
        this.$axios({
          method: 'get',
          url: '/system/department/list'
        }).then(res => {
          this.deptList = res.data;
        })
      },
      cancle(){
        this.$emit('cancle');
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$axios({
              method: 'post',
              url: '/system/department/add',
              data: this.addForm
            }).then(res => {
              if(res.code == 200) {
                this.$message.success('添加部门成功');
                this.$emit('cancle');
                this.$emit('refresh');
              }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
    }
  }
</script>

<style scoped>
  .el-form {
    width: 86%;
    margin:0 auto;
    margin-top: 10px;
    /* padding:0 30px; */
  }
  .el-form-item {
    margin: 12px 0;
  }

</style>
